<?php
namespace Home\Controller;

class UserController extends CommonController{

	public function index(){

      $list = D('User')->state($this->user['id']);
      $this->assign('list',$list);
		$this->display();
	}

    public function user_info(){

        $this->display();
    }

	public function auth_info(){
      
		$this->display();
	}

	public function account(){

		$this->display();
	}
	public function order_pay(){
		
		$this->display();
	}
	public function order_send(){
		
		$this->display();
	}
	
	public function order_confirm(){
		
		$this->display();
	}
	
	public function order_complete(){
		
		$this->display();
	}
	public function order_refund(){
		
		$this->display();
	}
	public function turn_log(){
		
		$this->display();
	}

    //提现
    public function extract(){
        $money = I('post.money');
        $money < $this->user['balance'] && $this->error('余额不足不能提现');
        $data['user_id'] = $this->user['id'];
        $data['pay_type'] = 6;
        $data['pay_value'] = $money;
        $res = D('PayLog')->add($data);
        $res === false ? $thsi->error('提现失败') : $this->success('提现成功');
    }

    //证件认证
    public function auth_card_info(){
        $this->assign('info',D('User')->where(array('id'=>$this->user['id']))->find());
        $this->display();
    }
    

    //积分列表
    public function integral_info(){
        //查出所有日期
        $data = D('CentLog')->field('create_time')->where(array('user_id'=>$this->user['id']))->group('left(create_time,7)')->select();
        $list = array();
        foreach($data as $val){
            $list[] = substr($val['create_time'],0,7);
        }
        //根据日期查出天数和数据
        $all = array();
        foreach($list as $value){
            $day_data = D('CentLog')->field('create_time')->where(array('user_id'=>$this->user['id'],'left(create_time,7)'=>$value))->group('left(create_time,10)')->select();
            $days = array();
            foreach ($day_data as $val_day) {
                $days[] = substr($val_day['create_time'],0,10);
            }
            $datas = array();
            $sum = 0;
            foreach ($days as $val) {
                $rows = D('CentLog')->where(array('user_id'=>$this->user['id'],'left(create_time,10)'=>$val))->select();
                foreach($rows as $v){
                    $v['type'] == '1' && $sum += $v['cent_value'];
                    $v['type'] == '2' && $sum -= $v['cent_value'];
                }
                $datas[$val] = $rows;
            }
            $all[$value]['datas'] = $datas;
            $all[$value]['sum'] = $sum;
            $all[$value]['status'] = $sum >= 0 ? '收入' : '支出';
        }  
        //当前积分
        $this->assign('all',$all);
        $this->display();
    }

	public function feedback(){
        
		$this->display();
	}

	public function address(){

		I('get.type') && session('address',I('server.HTTP_REFERER'));//记录跳转地址；
		session('basic_order') && session('address',U('Order/edit_order'));
		$this->assign('address',D('Address')->where(array('user_id'=>$this->user['id']))->select());
		$this->display();
	}
	
	public function address_save(){
		if(IS_POST){
			$data = I('post.info');
			D('Address')->create($data) || $this->error(D('Address')->getError());
			$data['is_default'] == '1' && D('Address')->where(array('user_id'=>$this->user['id']))->save(array('is_default'=>'2'));
			$result = D('Address')->saveData($data);
			//指定回调地址
			$redirect_url = U('address');
			if(session('basic_order')){
				$data['id'] && $address_id = $data['id'];
				$address_id || $address_id = D('Address')->where(array('user_id'=>$this->user['id']))->order('create_time desc')->getField('id');
				$redirect_url = U('Order/edit_order',array('address_id'=>$address_id));
			}
			if(session('address')){
				$data['id'] && $address_id = $data['id'];
				$address_id || $address_id = D('Address')->where(array('user_id'=>$this->user['id']))->order('create_time desc')->getField('id');
				$redirect_url = session('address').'?address_id='.$address_id;
			}
			$result ? $this->success('保存成功!',$redirect_url) : $this->error('保存失败！');
		}else{
			$data = array();
			I('get.id') && $data = D('Address')->where(array('id'=>(int)I('get.id')))->find();
			$this->assign('data',$data);
			$this->display();
		}
	}
	public function default_address(){
		I('post.id') || $this->error('参数缺失！');
		D('Address')->where(array('user_id'=>$this->user['id'],'is_default'=>'1'))->save(array('is_default'=>'2'));
		$res = D('Address')->where(array('id'=>(int)I('post.id')))->save(array('is_default'=>'1'));
		$res ? $this->success('') : $this->error('');
	}
	public function delete_address(){
		I('post.id') || $this->error('参数缺失！');
		$res = D('Address')->where(array('id'=>(int)I('post.id')))->delete();
		$res ? $this->success('删除成功！') : $this->error('删除失败！');
	}

    //更换手机号
    public function replay_phone(){
        $this->assign('user',D('User')->where(array('id'=>$this->user['id']))->find());
        $this->display();
    }

    public function getSmsCode(){
        $phone = I('post.phone');
        $random = mt_rand(100000, 999999);
        $msg = '您的验证码是：'.$random.'有效时间为5分钟,请尽快验证';
        session('code',$random);
        session('code_time',time());
        sendSMS($phone,$msg);
    }
    //实名认证
    public function verify(){
       $res = $this->checkSmsCode();
       $res || $this->error('验证码已过期请重新输入');
       if(I('post.code') != session('code')) $this->error('验证码不正确');
       $info = D('User')->where(array('id'=>$this->user['id']))->save(array('mobile'=>I('post.phone'),'rel_name'=>I('post.name'),'is_validate'=>1));
       $redirect_url = U('User/auth_success');
       session('basic_order') && $redirect_url = U('Order/edit_order');
       $info ==1 ? $this->success('验证成功',$redirect_url) : $this->error('验证失败');
    }

    public function save_phone(){
        $res = $this->checkSmsCode();
        $res || $this->error('验证码已过期请重新输入');
        if(I('post.code') != session('code')) $this->error('验证码不正确');
         $info = D('User')->where(array('id'=>$this->user['id']))->save(array('mobile'=>I('post.phone')));
       $info ==1 ? $this->success('更换成功',U('User/index')) : $this->error('更换失败');
    }

    //投诉与建议
    public function proposal(){

        if(!empty(I('post.image_name'))){
            $img = I ( 'post.image_name' );
            foreach ( $img as $k => $v ) {
                $image [] = $this->saveMedia ( $v );
            }
        $data ['pics'] = implode ( ',', $image );
        }
        $data['content'] = I('post.content');
        $data['user_id'] = $this->user['id'];
        $res = D('Feedback')->add($data);
        $res > 1 ? $this->success('建议成功',U('User/index')) : $this->error('建议不成功');
    }

     public function card(){

        !I('post.image_name') && $this->error('请上传身份证明正面照');
        $img = I ( 'post.image_name' );
        foreach ( $img as $k => $v ) {
            $image [] = $this->saveMedia ( $v );
        }
        $res = D('User')->where(array('id'=>$this->user['id']))->save(array('card_number'=>I('post.card_number'),'card_fpic'=>$image[0],'card_bpic'=>$image[1]));
        $res == 1 ? $this->success('建议成功',U('User/index')) : $this->error('建议不成功');
    }

    public function save_image(){
        $headimgurl = $this->saveMedia(I('post.id'));
        $res = D('User')->where(array('id'=>$this->user['id']))->save(array('headimgurl'=>$headimgurl));
        $res == 1 ? $this->success('更换成功',U('User/index')) : $this->error('更换失败');
    }

     public function save_name(){
       
        $res = D('User')->where(array('id'=>$this->user['id']))->save(array('nickname'=>I('post.name')));
        $res == 1 ? $this->success('更换成功',U('User/index')) : $this->error('更换失败');
    }

    // 处理微信图片上传
    public function saveMedia($id) {
        $info = $this->wechat->getMedia ( $id );
        if (! $info)     return '';
        $file = './Upload/home/' . date ( 'Y-m-d' ) . '/';
        if (! file_exists ( $file ))
            @mkdir ( $file, 0777 );
        $filename = substr ( md5 ( date ( 'Y-m-d H:i:s' ) ), 0, 16 ) . rand ( 1000, 9999 ) . '.jpg';
        $local_path = $file . $filename;
        file_put_contents ( $local_path, $info ); // 保存图片资源
        return substr ( $local_path, 1 );
    }



    //判断验证码是否过期
    private function checkSmsCode(){
        $diff_time = time()-session('code_time');
        if($diff_time > C('CODE_TIME')){
            return false;
        }else{
            return true;
        }
    }
}